package com.bt.springboot.common.util;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.bt.springboot.entity.Message;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zkx
 * @Date 2023/5/6 14:48
 */
@Slf4j
@Component
public class SocketUtil {

	/**
	 * 暂且把用户&客户端信息存在缓存
	 */
	public static ConcurrentHashMap<String, SocketIOClient> connectMap = new ConcurrentHashMap<>();

	@OnEvent(value = "CHANNEL_SYSTEM")
	public void systemDataListener(String receiveMsg) {
		if (StrUtil.isBlank(receiveMsg)) {
			return;
		}
		Message message = JSON.parseObject(receiveMsg, Message.class);
		log.info("收到用户：{} 推送到系统频道的一条消息：{}", message.getFrom(), message.getContent());
	}

	public void sendToAll(Map<String, Object> msg, String sendChannel) {
		if (connectMap.isEmpty()){
			return;
		}

		// 给这个频道的每个客户端发送消息
		for (Map.Entry<String, SocketIOClient> entry : connectMap.entrySet()) {
			entry.getValue().sendEvent(sendChannel,msg);
		}
	}

	public void sendToOne(String userFlag,Map<String,Object> msg,String sendChannel){
		// 拿出某个客户端信息
		SocketIOClient socketClient = getSocketClient(userFlag);
		if (Objects.nonNull(socketClient)){
			// 单独发送消息
			socketClient.sendEvent(sendChannel,msg);
		}
	}

	public SocketIOClient getSocketClient(String userFlag){
		SocketIOClient client = null;
		if (CharSequenceUtil.isNotBlank(userFlag) && !connectMap.isEmpty()){
			for (String key : connectMap.keySet()){
				if (userFlag.equals(key)){
					client = connectMap.get(key);
				}
			}
		}
		return client;
	}

}
